package com.netty.demo.client.demo.netty;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioDatagramChannel;
import io.netty.util.CharsetUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.net.InetSocketAddress;
import java.util.Random;

/**
 * @author Administrator 余秀良
 * @version 1.0
 * <p>date: 2019年09月21日  11:52 </p>
 * <p>address: 四川成都 </p>
 */
@Component
@Slf4j
public class NettyUdpClient {
    private final EventLoopGroup eventLoopGroup;
    private final Bootstrap bootstrap;

    public NettyUdpClient() {
        eventLoopGroup = new NioEventLoopGroup();
        bootstrap = new Bootstrap();
        //表明本应用发送的报文并没有一个确定的目的地，也就是进行广播
        InetSocketAddress inetSocketAddress = new InetSocketAddress("192.168.2.153", 8002);
        bootstrap.group(eventLoopGroup)
                .channel(NioDatagramChannel.class)
                .option(ChannelOption.SO_BROADCAST, true)
                .handler(new ClientEncoder(inetSocketAddress));
    }

    public static void main(String[] args) throws Exception {
        //创建并启动一个新的的实例
        NettyUdpClient nettyUdpClient = new NettyUdpClient();
        try {
            nettyUdpClient.run();
        } finally {
            nettyUdpClient.stop();
        }
    }

    public void stop() {
        eventLoopGroup.shutdownGracefully();
    }

    public void run() throws Exception {
        //绑定 Channel
        Channel ch = bootstrap.bind(9090).sync().channel();
        long count = 0;
        //启动主处理循环，模拟日志发送
        while (true) {
            long id = ++count;
            String msg = RequestMessage.getMsg();
            System.out.println("发送消息->  " + msg);
            RequestProtocol requestProtocol = new RequestProtocol();
            requestProtocol.setMessageId(id);
            requestProtocol.setHead(0X110);
            requestProtocol.setLength(msg.length());
            requestProtocol.setTime(System.currentTimeMillis());
            Random random = new Random();
            int i = random.nextInt(12);
            requestProtocol.setCmd((short) 3);
            requestProtocol.setData(msg.getBytes(CharsetUtil.UTF_8));
            ch.writeAndFlush(requestProtocol);
            try {
                //休眠，如果被中断，则退出循环；
                Thread.sleep(10000);
            } catch (InterruptedException e) {
                boolean interrupted = Thread.interrupted();
                System.out.println(interrupted);
                break;
            }
        }
    }
}
